<!DOCTYPE html>
<html lang="zh_cn">
<head>
          <title>来玩魔王的咚</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charset="utf-8" />
        <!-- twitter card metadata -->
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/images/mowang.png">
<meta name="twitter:site" content="">
<meta name="twitter:title" content="Ansible 配置文件">
<meta name="twitter:description" content="<p>配置文件：配置文件位置和优先级，配置文件模板，分类介绍配置；Inventory配置：定义主机和组，主机变量，组变量，默认组，组的嵌套，多重变量定义，用于SSH连接的参数，验证变量的值</p>">
        <!-- OG Tags -->
<meta property="og:url" content="/ansible-config-and-inventory.html"/>
<meta property="og:title" content="来玩魔王的咚 | Ansible 配置文件" />
<meta property="og:description" content="<p>配置文件：配置文件位置和优先级，配置文件模板，分类介绍配置；Inventory配置：定义主机和组，主机变量，组变量，默认组，组的嵌套，多重变量定义，用于SSH连接的参数，验证变量的值</p>" />
        <!-- favicon -->
        <link rel="icon" type="image/png" href="/images/mowang.png">
        <!-- moment.js for date formatting -->
        <script src="/theme/js/moment.js"></script>
        <!-- css -->
        <link rel="stylesheet" type="text/css" href="/theme/css/main.css" />
        <!-- 左边的menu，如果页面高度不够，就跟着滚动，否则文章分类显示不全 -->
        <link rel="stylesheet" type="text/css" href="/theme/css/mycss/menu.css" />
		<script>
			
                /*! grunt-grunticon Stylesheet Loader - v2.1.2 | https://github.com/filamentgroup/grunticon | (c) 2015 Scott Jehl, Filament Group, Inc. | MIT license. */
    
    (function(e){function t(t,n,r,o){"use strict";function a(){for(var e,n=0;u.length>n;n++)u[n].href&&u[n].href.indexOf(t)>-1&&(e=!0);e?i.media=r||"all":setTimeout(a)}var i=e.document.createElement("link"),l=n||e.document.getElementsByTagName("script")[0],u=e.document.styleSheets;return i.rel="stylesheet",i.href=t,i.media="only x",i.onload=o||null,l.parentNode.insertBefore(i,l),a(),i}var n=function(r,o){"use strict";if(r&&3===r.length){var a=e.navigator,i=e.Image,l=!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")||e.opera&&-1===a.userAgent.indexOf("Chrome")||-1!==a.userAgent.indexOf("Series40")),u=new i;u.onerror=function(){n.method="png",n.href=r[2],t(r[2])},u.onload=function(){var e=1===u.width&&1===u.height,a=r[e&&l?0:e?1:2];n.method=e&&l?"svg":e?"datapng":"png",n.href=a,t(a,null,null,o)},u.src="",document.documentElement.className+=" grunticon"}};n.loadCSS=t,e.grunticon=n})(this);(function(e,t){"use strict";var n=t.document,r="grunticon:",o=function(e){if(n.attachEvent?"complete"===n.readyState:"loading"!==n.readyState)e();else{var t=!1;n.addEventListener("readystatechange",function(){t||(t=!0,e())},!1)}},a=function(e){return t.document.querySelector('link[href$="'+e+'"]')},c=function(e){var t,n,o,a,c,i,u={};if(t=e.sheet,!t)return u;n=t.cssRules?t.cssRules:t.rules;for(var l=0;n.length>l;l++)o=n[l].cssText,a=r+n[l].selectorText,c=o.split(");")[0].match(/US\-ASCII\,([^"']+)/),c&&c[1]&&(i=decodeURIComponent(c[1]),u[a]=i);return u},i=function(e){var t,o,a;o="data-grunticon-embed";for(var c in e)if(a=c.slice(r.length),t=n.querySelectorAll(a+"["+o+"]"),t.length)for(var i=0;t.length>i;i++)t[i].innerHTML=e[c],t[i].style.backgroundImage="none",t[i].removeAttribute(o);return t},u=function(t){"svg"===e.method&&o(function(){i(c(a(e.href))),"function"==typeof t&&t()})};e.embedIcons=i,e.getCSS=a,e.getIcons=c,e.ready=o,e.svgLoadedCallback=u,e.embedSVG=u})(grunticon,this);
                
                grunticon(["/theme/css/icons.data.svg.css", "/theme/css/icons.data.png.css", "/theme/css/icons.fallback.css"]);
            </script>
        <noscript><link href="/theme/css/icons.fallback.css" rel="stylesheet"></noscript>
        <!-- menu toggle javascript -->
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", initMenu);
            
            function initMenu(){
                var menu = document.getElementById("menu");
                var menulink = document.getElementById("menu-link");
                menulink.addEventListener("click", function toggleMenu(){
                        window.event.preventDefault();
                        menulink.classList.toggle('active');
                        menu.classList.toggle('active');              
                    });
            };
        </script>
        <!-- 不蒜子 -->
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    <meta name="description" content="<p>配置文件：配置文件位置和优先级，配置文件模板，分类介绍配置；Inventory配置：定义主机和组，主机变量，组变量，默认组，组的嵌套，多重变量定义，用于SSH连接的参数，验证变量的值</p>" />

    <meta name="tags" content="ansible" />
  <!-- 替换部分base的样式，看文章时，要再宽一点，右边有很多空间可以撑开 -->
  <link rel="stylesheet" type="text/css" href="/theme/css/mycss/article.css" />

</head>
<body>
    <div role="banner" id="masthead">
        <header>
            <a href="/"><img src="/images/mowang.png" alt="McManus Logo"></a>
                <h1>来玩魔王的咚@骑士救兵</h1>
            <a href="#menu" id="menu-link">more stuff</a>
            <nav id="menu">
                <ul>
                        <li><a href="/tags">tags</a></li>
                            <li><a href="/category/cloud.html">Cloud</a></li>
                            <li><a href="/category/docker.html">Docker</a></li>
                            <li><a href="/category/go.html">Go</a></li>
                            <li><a href="/category/linux.html">Linux</a></li>
                            <li><a href="/category/python.html">Python</a></li>
                            <li><a href="/category/xue-xi-bi-ji.html">学习笔记</a></li>
                            <li class="active"><a href="/category/yun-wei-zi-dong-hua.html">运维自动化</a></li>
                </ul>
            </nav>
        </header>
    </div>
        <div class="page" role="main">
  <div class="article" role="article">
    <article>
        <footer>
            <a name="top"></a>
            <p>
              <time datetime=" 2019-08-23 09:43:51+08:00">
                <script>document.write(moment('2019-08-23 09:43:51+08:00').format('LL'));</script>
              </time>
              ~
              <time datetime=" 2019-08-23 09:43:51+08:00">
                <script>document.write(moment('2021-06-23 14:30:00+08:00').format('LL'));</script>
              </time>
            </p>
        </footer>
        <header>
          <h2>
            Ansible 配置文件
          </h2>
        </header>
      <div class="content">
         <div class="toc">
<ul>
<li><a href="#pei-zhi-wen-jian-xiang-jie">配置文件详解</a><ul>
<li><a href="#pei-zhi-wen-jian-de-wei-zhi">配置文件的位置</a></li>
<li><a href="#huo-qu-pei-zhi-wen-jian-mu-ban">获取配置文件模板</a></li>
<li><a href="#defaults">[defaults]</a></li>
<li><a href="#privilege_escalation">[privilege_escalation]</a></li>
<li><a href="#paramiko_connection">[paramiko_connection]</a></li>
<li><a href="#ssh_connection">[ssh_connection]</a></li>
<li><a href="#accelerate">[accelerate]</a></li>
<li><a href="#selinux">[selinux]</a></li>
<li><a href="#colors">[colors]</a></li>
</ul>
</li>
<li><a href="#inventory-pei-zhi-xiang-jie">Inventory 配置详解</a><ul>
<li><a href="#zhi-xiang-wen-jian-jia-aggregating-inventory-sources-with-a-directory">指向文件夹(Aggregating inventory sources with a directory)</a></li>
<li><a href="#ding-yi-zhu-ji-he-zu">定义主机和组</a></li>
<li><a href="#zi-ding-yi-bian-liang">自定义变量</a></li>
<li><a href="#zu-de-qian-tao">组的嵌套</a></li>
<li><a href="#duo-zhong-bian-liang-ding-yi">多重变量定义</a></li>
<li><a href="#yong-yu-ssh-lian-jie-de-can-shu">用于SSH连接的参数</a></li>
<li><a href="#yan-zheng-bian-liang-de-zhi">验证变量的值</a></li>
</ul>
</li>
</ul>
</div>
<h3 id="pei-zhi-wen-jian-xiang-jie"><a class="toclink" href="#pei-zhi-wen-jian-xiang-jie">配置文件详解</a></h3>
<p>配置文件中大多数都是注释行默认配置项。文件遵循INI格式，分为几个类别的配置，下面会分别介绍。<br>
在那之前，先看一下配置文件存放的位置，以及如何从官网获取配置文件模板。  </p>
<h4 id="pei-zhi-wen-jian-de-wei-zhi"><a class="toclink" href="#pei-zhi-wen-jian-de-wei-zhi">配置文件的位置</a></h4>
<p>Ansible只有一个配置文件ansible.cfg。配置文件可以存在于多个位置，按下面的顺序查找到的第一个生效：</p>
<ul>
<li>ANSIBLE_CONFIG (环境变量指定)</li>
<li>ansible.cfg (当前命令执行目录)</li>
<li>~/.ansible.cfg (用户家目录下)</li>
<li>/etc/ansible/ansible.cfg</li>
</ul>
<p>只有最先找到的配置文件会生效。另外环境变量的优先级比配置文件高，而且可以一个一个单独设置。每个配置项对应的环境变量的名称，可以在下面的官方文档中查到：<br>
<a href="https://docs.ansible.com/ansible/latest/reference_appendices/config.html#common-options">https://docs.ansible.com/ansible/latest/reference_appendices/config.html#common-options</a><br>
另外每个变量的默认值也是在这里查。  </p>
<p>还有命令行参数指定的方式，这个的优先级比上面的配置方式都高。不过在playbook中指定的设置优先级更高，不会被命令行参数覆盖。  </p>
<h4 id="huo-qu-pei-zhi-wen-jian-mu-ban"><a class="toclink" href="#huo-qu-pei-zhi-wen-jian-mu-ban">获取配置文件模板</a></h4>
<p>Ansible安装后，默认会在/etc/ansible/目录下生成配置文件。但是如果是通过pip或者是源码安装的话，就没有这个文件，需要手动创建。<br>
可以到官方的github上去下一个最新的：</p>
<div class="highlight"><pre><span></span><code>$ mkdir /etc/ansible
$ <span class="nb">cd</span> /etc/ansible
$ wget https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
</code></pre></div>

<h4 id="defaults"><a class="toclink" href="#defaults">[defaults]</a></h4>
<p>定义常规的连接类配置：</p>
<div class="highlight"><pre><span></span><code><span class="k">[defaults]</span><span class="w"></span>

<span class="c1"># some basic default values...</span><span class="w"></span>

<span class="c1">#inventory      = /etc/ansible/hosts  # 定义Inventory，用于定义主机列表配置</span><span class="w"></span>
<span class="c1">#library        = /usr/share/my_modules/  # 自定了lib库存放目录</span><span class="w"></span>
<span class="c1">#module_utils   = /usr/share/my_module_utils/</span><span class="w"></span>
<span class="c1">#remote_tmp     = ~/.ansible/tmp  # 临时文件远程主机存放目录</span><span class="w"></span>
<span class="c1">#local_tmp      = ~/.ansible/tmp  # 临时文件本地存放目录</span><span class="w"></span>
<span class="c1">#plugin_filters_cfg = /etc/ansible/plugin_filters.yml</span><span class="w"></span>
<span class="c1">#forks          = 5  # 默认开启的并发数</span><span class="w"></span>
<span class="c1">#poll_interval  = 15  # 默认轮询时间间隔</span><span class="w"></span>
<span class="c1">#sudo_user      = root  # 默认sudo用户</span><span class="w"></span>
<span class="c1">#ask_sudo_pass = True  # 是否需要sudo密码</span><span class="w"></span>
<span class="c1">#ask_pass      = True  # 是否需要密码</span><span class="w"></span>
<span class="c1">#transport      = smart</span><span class="w"></span>
<span class="c1">#remote_port    = 22</span><span class="w"></span>
<span class="c1">#module_lang    = C</span><span class="w"></span>
<span class="c1">#module_set_locale = False</span><span class="w"></span>

<span class="c1"># additional paths to search for roles in, colon separated</span><span class="w"></span>
<span class="c1">#roles_path    = /etc/ansible/roles  # 默认下载的Roles存在的目录</span><span class="w"></span>

<span class="c1"># uncomment this to disable SSH key host checking</span><span class="w"></span>
<span class="c1">#host_key_checking = False  # 首次连接是否需要检查key认证，建议放开注释设为False</span><span class="w"></span>

<span class="c1"># SSH timeout</span><span class="w"></span>
<span class="c1">#timeout = 10  # 默认超时时间</span><span class="w"></span>

<span class="c1"># logging is off by default unless this path is defined</span><span class="w"></span>
<span class="c1"># if so defined, consider logrotate</span><span class="w"></span>
<span class="c1">#log_path = /var/log/ansible.log  # 执行日志存放目录</span><span class="w"></span>

<span class="c1"># default module name for /usr/bin/ansible</span><span class="w"></span>
<span class="c1">#module_name = command  # 默认执行模块</span><span class="w"></span>

<span class="c1"># set plugin path directories here, separate with colons</span><span class="w"></span>
<span class="c1">#action_plugins     = /usr/share/ansible/plugins/action  # 各类插件的存放目录</span><span class="w"></span>
<span class="c1">#become_plugins     = /usr/share/ansible/plugins/become</span><span class="w"></span>
<span class="c1">#cache_plugins      = /usr/share/ansible/plugins/cache</span><span class="w"></span>
<span class="c1">#callback_plugins   = /usr/share/ansible/plugins/callback</span><span class="w"></span>
<span class="c1">#connection_plugins = /usr/share/ansible/plugins/connection</span><span class="w"></span>
<span class="c1">#lookup_plugins     = /usr/share/ansible/plugins/lookup</span><span class="w"></span>
<span class="c1">#inventory_plugins  = /usr/share/ansible/plugins/inventory</span><span class="w"></span>
<span class="c1">#vars_plugins       = /usr/share/ansible/plugins/vars</span><span class="w"></span>
<span class="c1">#filter_plugins     = /usr/share/ansible/plugins/filter</span><span class="w"></span>
<span class="c1">#test_plugins       = /usr/share/ansible/plugins/test</span><span class="w"></span>
<span class="c1">#terminal_plugins   = /usr/share/ansible/plugins/terminal</span><span class="w"></span>
<span class="c1">#strategy_plugins   = /usr/share/ansible/plugins/strategy</span><span class="w"></span>

<span class="c1"># if set to a persistent type (not &#39;memory&#39;, for example &#39;redis&#39;) fact values</span><span class="w"></span>
<span class="c1"># from previous runs in Ansible will be stored.  This may be useful when</span><span class="w"></span>
<span class="c1"># wanting to use, for example, IP information from one group of servers</span><span class="w"></span>
<span class="c1"># without having to talk to them in the same playbook run to get their</span><span class="w"></span>
<span class="c1"># current IP information.</span><span class="w"></span>
<span class="c1">#fact_caching = memory  # getfact 缓存的主机信息存放方式</span><span class="w"></span>

<span class="c1"># retry files</span><span class="w"></span>
<span class="c1"># When a playbook fails a .retry file can be created that will be placed in ~/</span><span class="w"></span>
<span class="c1"># You can enable this feature by setting retry_files_enabled to True</span><span class="w"></span>
<span class="c1"># and you can change the location of the files by setting retry_files_save_path</span><span class="w"></span>

<span class="c1">#retry_files_enabled = False</span><span class="w"></span>
<span class="c1">#retry_files_save_path = ~/.ansible-retry  # 错误重启文件存放目录</span><span class="w"></span>
</code></pre></div>

<p>上面这些配置多数都保持默认即可。只有一项<code>host_key_checking = False</code>可以放开注释。  </p>
<h4 id="privilege_escalation"><a class="toclink" href="#privilege_escalation">[privilege_escalation]</a></h4>
<p>处于安全考虑，有时候不希望直接以root用户直接部署应用，这时候就需要给普通用户sudo权限。<br>
这部分配置主要就是针对sudo用户提权的配置：</p>
<div class="highlight"><pre><span></span><code><span class="k">[privilege_escalation]</span><span class="w"></span>
<span class="c1">#become=True  # 是否sudo</span><span class="w"></span>
<span class="c1">#become_method=sudo  # sudo方式</span><span class="w"></span>
<span class="c1">#become_user=root  # sudo后变为root用户</span><span class="w"></span>
<span class="c1">#become_ask_pass=False  # sodu后是否验证密码</span><span class="w"></span>
</code></pre></div>

<h4 id="paramiko_connection"><a class="toclink" href="#paramiko_connection">[paramiko_connection]</a></h4>
<p>这部分功能不常用了，了解下把：</p>
<div class="highlight"><pre><span></span><code><span class="k">[paramiko_connection]</span><span class="w"></span>

<span class="c1"># uncomment this line to cause the paramiko connection plugin to not record new host</span><span class="w"></span>
<span class="c1"># keys encountered.  Increases performance on new host additions.  Setting works independently of the</span><span class="w"></span>
<span class="c1"># host key checking setting above.</span><span class="w"></span>
<span class="c1">#record_host_keys=False  # 不记录新主机的key以提升效率</span><span class="w"></span>

<span class="c1"># by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this</span><span class="w"></span>
<span class="c1"># line to disable this behaviour.</span><span class="w"></span>
<span class="c1">#pty=False  # 禁用sudo功能</span><span class="w"></span>
</code></pre></div>

<h4 id="ssh_connection"><a class="toclink" href="#ssh_connection">[ssh_connection]</a></h4>
<p>Ansible默认使用ssh连接主机，这里是SSH连接的一些配置：</p>
<div class="highlight"><pre><span></span><code><span class="c1"># Enabling pipelining reduces the number of SSH operations required to</span><span class="w"></span>
<span class="c1"># execute a module on the remote server. This can result in a significant</span><span class="w"></span>
<span class="c1"># performance improvement when enabled, however when using &quot;sudo:&quot; you must</span><span class="w"></span>
<span class="c1"># first disable &#39;requiretty&#39; in /etc/sudoers</span><span class="w"></span>
<span class="c1">#</span><span class="w"></span>
<span class="c1"># By default, this option is disabled to preserve compatibility with</span><span class="w"></span>
<span class="c1"># sudoers configurations that have requiretty (the default on many distros).</span><span class="w"></span>
<span class="c1">#</span><span class="w"></span>
<span class="c1">#pipelining = False  # 管道加速功能，需配合requiretty使用方可生效</span><span class="w"></span>
</code></pre></div>

<p>这块的配置项也不多，多数还是保持默认即可。  </p>
<h4 id="accelerate"><a class="toclink" href="#accelerate">[accelerate]</a></h4>
<p>Ansible连接加速相关配置：</p>
<div class="highlight"><pre><span></span><code><span class="k">[accelerate]</span><span class="w"></span>
<span class="c1">#accelerate_port = 5099  # 加速连接端口</span><span class="w"></span>
<span class="c1">#accelerate_timeout = 30  # 命令执行超时时间，单位秒</span><span class="w"></span>
<span class="c1">#accelerate_connect_timeout = 5.0  # 连接超时时间，单位秒</span><span class="w"></span>

<span class="c1"># The daemon timeout is measured in minutes. This time is measured</span><span class="w"></span>
<span class="c1"># from the last activity to the accelerate daemon.</span><span class="w"></span>
<span class="c1">#accelerate_daemon_timeout = 30  # 上一个活动连接的时间，单位分数</span><span class="w"></span>

<span class="c1"># If set to yes, accelerate_multi_key will allow multiple</span><span class="w"></span>
<span class="c1"># private keys to be uploaded to it, though each user must</span><span class="w"></span>
<span class="c1"># have access to the system via SSH to add a new key. The default</span><span class="w"></span>
<span class="c1"># is &quot;no&quot;.</span><span class="w"></span>
<span class="c1">#accelerate_multi_key = yes</span><span class="w"></span>
</code></pre></div>

<p>这里的配置项在提供Ansible连接速度时会涉及，多数还是保持默认。  </p>
<h4 id="selinux"><a class="toclink" href="#selinux">[selinux]</a></h4>
<p>selinux几乎不会用，配置上还是保持默认：</p>
<div class="highlight"><pre><span></span><code><span class="c1"># Set this to yes to allow libvirt_lxc connections to work without SELinux.</span><span class="w"></span>
<span class="c1">#libvirt_lxc_noseclabel = yes</span><span class="w"></span>
</code></pre></div>

<h4 id="colors"><a class="toclink" href="#colors">[colors]</a></h4>
<p>输出结果颜色的设置。原本的配置已经很好了，几乎不用修改，保持默认：</p>
<div class="highlight"><pre><span></span><code><span class="k">[colors]</span><span class="w"></span>
<span class="c1">#highlight = white</span><span class="w"></span>
<span class="c1">#verbose = blue</span><span class="w"></span>
<span class="c1">#warn = bright purple</span><span class="w"></span>
<span class="c1">#error = red</span><span class="w"></span>
<span class="c1">#debug = dark gray</span><span class="w"></span>
<span class="c1">#deprecate = purple</span><span class="w"></span>
<span class="c1">#skip = cyan</span><span class="w"></span>
<span class="c1">#unreachable = red</span><span class="w"></span>
<span class="c1">#ok = green</span><span class="w"></span>
<span class="c1">#changed = yellow</span><span class="w"></span>
<span class="c1">#diff_add = green</span><span class="w"></span>
<span class="c1">#diff_remove = red</span><span class="w"></span>
<span class="c1">#diff_lines = cyan</span><span class="w"></span>
</code></pre></div>

<h3 id="inventory-pei-zhi-xiang-jie"><a class="toclink" href="#inventory-pei-zhi-xiang-jie">Inventory 配置详解</a></h3>
<p>Inventory是Ansible管理主机的配置文件，默认位置是/etc/ansible/hosts，这个在ansible.cfg配置文件的开头有定义。<br>
另外在ansible命令行中可以使用-i参数来指定要使用的Inventory文件。<br>
注释：使用#来写注释内容。  </p>
<h4 id="zhi-xiang-wen-jian-jia-aggregating-inventory-sources-with-a-directory"><a class="toclink" href="#zhi-xiang-wen-jian-jia-aggregating-inventory-sources-with-a-directory">指向文件夹(Aggregating inventory sources with a directory)</a></h4>
<p>现在可以直接将Inventory指向一个文件夹，而不是某个文件。在目录中组合多个文件内的主机信息，每个文件可以是不同的格式，动态或静态的主机信息。<br>
<a href="https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#using-multiple-inventory-sources">https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#using-multiple-inventory-sources</a>  </p>
<h4 id="ding-yi-zhu-ji-he-zu"><a class="toclink" href="#ding-yi-zhu-ji-he-zu">定义主机和组</a></h4>
<p>写在中括号中的内部表示组名。主机名可以是IP地址也可以是Hostname。主机名可以出现多次，这样可以写到多个组里。<br>
如果主机使用了非默认的SSH端口，则可以在主机名后加冒号指定SSH端口号。<br>
配置示例：：</p>
<div class="highlight"><pre><span></span><code><span class="c1"># 配置示例</span><span class="w"></span>

<span class="c1"># 可以用IP地址</span><span class="w"></span>
<span class="na">192.168.1.1</span><span class="w"></span>

<span class="c1"># 也可以使用Hostname</span><span class="w"></span>
<span class="na">www.ansible.com</span><span class="w"></span>
<span class="na">docs.ansible.com:2222</span><span class="w"></span>

<span class="c1"># 使用中括号表示一个分组的开始，主机与主机之间可以有空行不影响分组</span><span class="w"></span>
<span class="k">[webservers]</span><span class="w"></span>
<span class="na">web1.ansible.com</span><span class="w"></span>

<span class="c1"># 用[10:20]表示连续的数组，包括10和20</span><span class="w"></span>
<span class="na">web[10:20].ansible.com</span><span class="w"></span>

<span class="k">[dbservers]</span><span class="w"></span>
<span class="na">db-a.ansible.com</span><span class="w"></span>
<span class="c1"># 也可以用中括号处理连续的字母</span><span class="w"></span>
<span class="na">db-[b:f].ansible.com</span><span class="w"></span>
</code></pre></div>

<h4 id="zi-ding-yi-bian-liang"><a class="toclink" href="#zi-ding-yi-bian-liang">自定义变量</a></h4>
<p>对于一些非标准化的配置需求，可以在Inventory配置中进行设置。这样可以满足对于主机的一些个性化设置要求。<br>
Ansible支持多种方式修改或自定义变量，Inventory是其中的一种修改方式。  </p>
<h5 id="ding-yi-zhu-ji-bian-liang"><a class="toclink" href="#ding-yi-zhu-ji-bian-liang">定义主机变量</a></h5>
<p>在定义主机时可以同时定义主机变量：</p>
<div class="highlight"><pre><span></span><code><span class="k">[webserverrs]</span><span class="w"></span>
<span class="na">web1.ansible.com http_port</span><span class="o">=</span><span class="s">8000  # 自定义http_port的端口号为8000</span><span class="w"></span>
</code></pre></div>

<h5 id="ding-yi-zu-bian-liang"><a class="toclink" href="#ding-yi-zu-bian-liang">定义组变量</a></h5>
<p>还可以定义组变量，同时对一组主机修改或自定义变量：</p>
<div class="highlight"><pre><span></span><code><span class="k">[groupservers]</span><span class="w"></span>
<span class="na">web1.ansible.com</span><span class="w"></span>
<span class="na">web2.ansible.com</span><span class="w"></span>

<span class="k">[groupservers:vars]</span><span class="w"></span>
<span class="na">http_port</span><span class="o">=</span><span class="s">8000</span><span class="w"></span>
</code></pre></div>

<p><strong>Default groups</strong>
Ansible还定义好了两个默认组：</p>
<ul>
<li>all: 包含所有主机</li>
<li>ungrouped: 包含没有组的所有主机</li>
</ul>
<h4 id="zu-de-qian-tao"><a class="toclink" href="#zu-de-qian-tao">组的嵌套</a></h4>
<p>Inventory中的组还可以包含其他的组，就是嵌套。嵌套时要在大组的名字后加上:children，表示嵌套的成员是组名而不是主机名：</p>
<div class="highlight"><pre><span></span><code><span class="k">[apache]</span><span class="w"></span>
<span class="na">httpd1.ansible.com</span><span class="w"></span>
<span class="na">httpd2.ansible.com</span><span class="w"></span>

<span class="k">[nginx]</span><span class="w"></span>
<span class="na">ngx1.ansible.com</span><span class="w"></span>
<span class="na">ngx2.ansible.com</span><span class="w"></span>

<span class="k">[webservers:children]</span><span class="w"></span>
<span class="na">apache</span><span class="w"></span>
<span class="na">nginx</span><span class="w"></span>

<span class="k">[webservers:vars]</span><span class="w"></span>
<span class="na">ntp_server</span><span class="o">=</span><span class="s">ntp1.aliyun.com</span><span class="w"></span>
</code></pre></div>

<p>对于嵌套的组也是可以设置组变量的，这个和普通的组变量一样。  </p>
<h4 id="duo-zhong-bian-liang-ding-yi"><a class="toclink" href="#duo-zhong-bian-liang-ding-yi">多重变量定义</a></h4>
<p>变量除了可以在Inventory中定义，还可以独立于Inventory文件之外单独定义到一个配置文件中。  </p>
<p>下面是设置变量的各种途径，按优先级顺序排列：</p>
<ol>
<li>command line values (eg “-u user”)</li>
<li>role defaults</li>
<li>inventory file or script group vars</li>
<li>inventory group_vars/all</li>
<li>playbook group_vars/all</li>
<li>inventory group_vars/*</li>
<li>playbook group_vars/*</li>
<li>inventory file or script host vars</li>
<li>inventory host_vars/*</li>
<li>playbook host_vars/*</li>
<li>host facts / cached set_facts</li>
<li>play vars</li>
<li>play vars_prompt</li>
<li>play vars_files</li>
<li>role vars (defined in role/vars/main.yml)</li>
<li>block vars (only for tasks in block)</li>
<li>task vars (only for the task)</li>
<li>include_vars</li>
<li>set_facts / registered vars</li>
<li>role (and include_role) params</li>
<li>include params</li>
<li>extra vars (always win precedence)</li>
</ol>
<p><a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#ansible-variable-precedence">https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#ansible-variable-precedence</a></p>
<p>比较常用的是如下4种：</p>
<ul>
<li>Inventory配置文件</li>
<li>Playbook中vars定义的区域</li>
<li>Roles中vars目录下的文件（roles/X/vars/main.yml）</li>
<li>group_vars和hosts_vars目录下的文件</li>
</ul>
<p>单独定义vars配置文件，比如有个主机foosball，同时属于raleigh和webservers组，那么变量定义在以主机名或组名定义的如下3个文件中都有效：</p>
<ul>
<li>/etc/ansible/group_vars/raleigh</li>
<li>/etc/ansible/group_vars/webservers</li>
<li>/etc/ansible/host_vars/foosball</li>
</ul>
<h4 id="yong-yu-ssh-lian-jie-de-can-shu"><a class="toclink" href="#yong-yu-ssh-lian-jie-de-can-shu">用于SSH连接的参数</a></h4>
<p>Ansible基于SSH连接Inventory中指定远程主机时，还内置了一些参数，用于指定连接时的交互方式，下面列举了比较常用的参数：</p>
<ul>
<li>ansible_ssh_host: 指定连接主机</li>
<li>ansible_ssh_port: 指定SSH连接端口，默认22</li>
<li>ansible_ssh_user: 指定SSH连接用户</li>
<li>ansible_ssh_pass: 指定SSH连接密码</li>
<li>ansible_ssh_private_key_file: 指定私钥文件</li>
</ul>
<p>连接要用到连接插件，插件会用到自己的变量，比如上面的这几个就是。下面的几个是通用的连接变量，这些变量插件也是可以识别的，效果是一样的。  </p>
<p>下面3个是通用的连接用的变量：</p>
<ul>
<li>ansible_host</li>
<li>ansible_port</li>
<li>ansible_user</li>
</ul>
<p>这里的3个是通用的，优先级上应该会被上面的专用的覆盖掉。  </p>
<p>SSH插件一共有哪些变量，这些变量的设置方式和对应的名称，包括默认值、环境变量、所有对应的变量名，可以查官方文档：<br>
<a href="https://docs.ansible.com/ansible/latest/plugins/connection/ssh.html#ssh-connection">https://docs.ansible.com/ansible/latest/plugins/connection/ssh.html#ssh-connection</a>  </p>
<p>所有的连接查看，看这里：<br>
<a href="https://docs.ansible.com/ansible/latest/plugins/connection.html?highlight=ansible_ssh_host">https://docs.ansible.com/ansible/latest/plugins/connection.html?highlight=ansible_ssh_host</a>  </p>
<h4 id="yan-zheng-bian-liang-de-zhi"><a class="toclink" href="#yan-zheng-bian-liang-de-zhi">验证变量的值</a></h4>
<p>把设备设置的参数打印出来，进行验证。  </p>
<h5 id="local"><a class="toclink" href="#local">local</a></h5>
<p>指定使用连接插件为locol，这样执行时不会连接到远程主机，而是直接在ansible程序的主机上运行。这个效果可以用hostname来验证：</p>
<div class="highlight"><pre><span></span><code><span class="gp">$ </span>ansible HOST -m <span class="nb">command</span> -a <span class="s2">&quot;hostname&quot;</span> -c <span class="nb">local</span>
</code></pre></div>

<p>指定连接为local后，执行command模块的hostname命令，就是在当前的ansible主机上运行，返回的结果也是当前ansible主机的主机名。  </p>
<h5 id="echo"><a class="toclink" href="#echo">echo</a></h5>
<p>然后再用echo命令把参数的值打印出来：</p>
<div class="highlight"><pre><span></span><code><span class="gp">$ </span>ansible HOST -m <span class="nb">command</span> -a <span class="s2">&quot;echo {{VAR_KEY}}&quot;</span> -c <span class="nb">local</span>
</code></pre></div>
      </div>
      <div class="back-to-top">
        <a href="/">HOME</a>
        <a href="#top">TOP</a>
      </div>
    </article>
  </div>
<!-- end article -->
<!-- 页面往下滚动一段之后才会显示TOC -->
<script>
  window.onscroll = function() {
    var tocbox = document.getElementsByClassName('toc')[0];
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    var osWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    // console.log(osTop)
    if (osTop>300 && osWidth>865) {
      tocbox.style.display = "block"
    }
    if (osTop<300 || osWidth<865) {
      tocbox.style.display = "none"
    }
  }
</script>
                <footer>
                    <div class="icons">
                    </div>
                    <span id="busuanzi_container_page_pv" style="padding: 10px">本文阅读量<span id="busuanzi_value_page_pv"></span>次</span>
                    <span id="busuanzi_container_site_pv" style="padding: 10px">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
                    <span id="busuanzi_container_site_uv" style="padding: 10px">本站总访客数<span id="busuanzi_value_site_uv"></span>人</span>
                    <p>© <script>document.write(moment().format('YYYY'));</script> 749B</p>
                </footer>
        </div>
</body>
</html>